package com.ivory.valley.common;

import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ivory.valley.util.HttpUtil;



public class MvcLogInterceptor {
	
		private Set<String> hideParamNames;
		
		public MvcLogInterceptor(Set<String> hideParamNames) {
			this.hideParamNames = hideParamNames;
		}

		public Object log(ProceedingJoinPoint point) throws Throwable {
			Log log=this.getLog(point);
			HttpServletRequest request=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
			log.info("[REQ]: url="+request.getRequestURI()+", param="+this.getReqParam(request));
			Object obj=point.proceed();
			log.info("[RES]: "+obj);
			return obj;
		}
		
		private Log getLog(ProceedingJoinPoint point){
			return LogFactory.getLog(point.getTarget().getClass().getName());
		}
		
		private Map<String, Object> getReqParam(HttpServletRequest request){			
			Map<String,Object> param=HttpUtil.getRequestParam(request);
			if(hideParamNames!=null){
				for(String name : hideParamNames){
					if(param.containsKey(name)){param.put(name, "****");}	
				}
			}
			return param;
		}

}
